package com.gpoint.rdp.door.CurrentPermission.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.core.entity.ResultMessage;
import com.gpoint.rdp.base.framework.page.PageList;
import com.gpoint.rdp.base.framework.page.PageResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gpoint.rdp.api.base.query.QueryFilter;
import com.gpoint.rdp.base.web.controller.GenericController;
import com.gpoint.rdp.base.web.json.PageJson;
import com.gpoint.rdp.base.web.util.RequestUtil;
import com.gpoint.rdp.base.web.util.RequestViewUtil;
import com.gpoint.rdp.common.DoorConfig;
import com.gpoint.rdp.door.CurrentPermission.service.CurrentPermissionService;
import com.gpoint.rdp.door.CurrentPermissionHis.persistence.entity.CurrentPermissionHisPo;
import com.gpoint.rdp.door.CurrentPermissionHis.repository.CurrentPermissionHisRepository;
import com.gpoint.rdp.door.doorPermission.persistence.dao.DoorPermissonTypeQueryDao;
import com.gpoint.rdp.door.doorPermission.persistence.dao.PermissTypeAndUserQueryDao;
import com.gpoint.rdp.door.doorPermission.persistence.entity.DoorPermissonTypePo;
import com.gpoint.rdp.door.doorPermission.persistence.entity.PermissTypeAndUserPo;
import com.gpoint.rdp.door.permissionPid.controller.Utils;
import com.gpoint.rdp.door.user.persistence.dao.CampusCardQueryDao;
import com.gpoint.rdp.door.user.persistence.entity.CampusCardPo;
import com.gpoint.rdp.door.user.service.CampusCardQueryService;
import com.gpoint.rdp.door.zoneCTL.repository.DoorZoneRepository;


import com.gpoint.rdp.door.CurrentPermission.service.CurrentPermissionQueryService;
import com.gpoint.rdp.door.CurrentPermission.domain.CurrentPermission;
import com.gpoint.rdp.door.CurrentPermission.persistence.dao.CurrentPermissionDao;
import com.gpoint.rdp.door.CurrentPermission.persistence.dao.CurrentPermissionQueryDao;
import com.gpoint.rdp.door.CurrentPermission.persistence.entity.CurrentPermissionPo;
import com.gpoint.rdp.door.CurrentPermission.repository.CurrentPermissionRepository;
import com.gpoint.rdp.base.core.util.AppUtil;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.JacksonUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.ParseException;


/**
 * TB_DOOR_CURRENTPERMISSION 控制类
 *
 *<pre> 
 * 开发公司：苏州东大金点信息技术有限公司
 * 开发人员：唐红锋
 * 邮箱地址：55872655@qq.com
 * 创建时间：2019-10-22 16:49:55
 * @author WIN10
 *</pre>
 */
@Controller
@RequestMapping("/rdp/CurrentPermission/currentPermission/")
public class CurrentPermissionController extends GenericController{
	@Resource
	private CurrentPermissionService currentPermissionService;
	@Resource
	private CurrentPermissionQueryService currentPermissionQueryService;
	
	@Resource
	private CampusCardQueryService campusCardQueryService;
	
	

	
	
//	@Resource
//	private PermissTypeAndUserQueryDao permissTypeAndUserQueryDao;
//	
//	
//	@Resource
//	private DoorPermissonTypeQueryDao doorPermissonTypeQueryDao;
//	
	
	@RequestMapping("list")
	 public ModelAndView list(HttpServletRequest request,HttpServletResponse response) throws Exception{
	  ModelAndView mv=getAutoView();
	  return mv;
	  
	 }
	
//	@Resource
//	private CurrentPermissionRepository currentPermissionRepository;
//	
//	@Resource
//	private CurrentPermissionHisRepository currentPermissionHisRepository;
	
	
	DoorConfig config=AppUtil.getBean(DoorConfig.class);
    String servicecode=config.getServicecode();
    
	
	@RequestMapping("listPid")
	 public ModelAndView listPid(HttpServletRequest request,HttpServletResponse response) throws Exception{
	  ModelAndView mv=new ModelAndView("/rdp/CurrentPermission/pidPermissionList.jsp");
	  return mv;
	  
	 }
	
	
    
    @RequestMapping("listPidPage")
	public @ResponseBody PageJson listPidPage(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		QueryFilter queryFilter = getQuerFilter(request);
		try{
			String begindate = RequestUtil.getString(request,"Q^ALLOCATEDTIME^DL");
			 String enddate=RequestUtil.getString(request, "Q^ALLOCATEDTIME^DG");
			 String sbegindate = RequestUtil.getString(request,"Q^DOWNTIME^DL");
			String senddate=RequestUtil.getString(request, "Q^DOWNTIME^DG");
				 
			 queryFilter.addParamsFilter("begin_ALLOCATEDTIME", Utils.string2Date(begindate));
			 queryFilter.addParamsFilter("end_ALLOCATEDTIME", Utils.string2Date(enddate));
			 queryFilter.addParamsFilter("begin_DOWNTIME", Utils.string2Date(sbegindate));
			 queryFilter.addParamsFilter("end_DOWNTIME", Utils.string2Date(senddate));
			 String listData=   this.currentPermissionQueryService.queryPidPage(queryFilter);
			 PageList<CurrentPermissionPo> currentPermissionList = null;
			if(JacksonUtil.isJsonObject(listData)){
				List<CurrentPermissionPo> list = CurrentPermissionPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				currentPermissionList = new PageList<CurrentPermissionPo>(list, pageResult);
			}
			
			return new PageJson(currentPermissionList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}

    
    
	/**
	 * 【TB_DOOR_CURRENTPERMISSION】列表(分页条件查询)数据
	 *
	 * @param request
	 * @param reponse
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("listJson")
	public @ResponseBody PageJson listJson(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		QueryFilter queryFilter = getQuerFilter(request);
		try{
			String begindate = RequestUtil.getString(request,"Q^ALLOCATEDTIME^DL");
			 String enddate=RequestUtil.getString(request, "Q^ALLOCATEDTIME^DG");
			
			 String sbegindate = RequestUtil.getString(request,"Q^DOWNTIME^DL");
			String senddate=RequestUtil.getString(request, "Q^DOWNTIME^DG");
				 
			 queryFilter.addParamsFilter("begin_ALLOCATEDTIME", Utils.string2Date(begindate));
			 queryFilter.addParamsFilter("end_ALLOCATEDTIME", Utils.string2Date(enddate));
			 queryFilter.addParamsFilter("begin_DOWNTIME", Utils.string2Date(sbegindate));
			 queryFilter.addParamsFilter("end_DOWNTIME", Utils.string2Date(senddate));
			
			 /*
			 //拼凑SQL：
			 if(begindate.length()!=0 && enddate.length()!=0 ) {
				 String sql =   "ALLOCATEDTIME >=  '"+begindate+"'"+"and ALLOCATEDTIME <=  '"+enddate+"'";
				 queryFilter.addParamsFilter("begin_ALLOCATEDTIME", Utils.string2Date(begindate));
				 queryFilter.addParamsFilter("end_ALLOCATEDTIME", Utils.string2Date(enddate));
				 queryFilter.addParamsFilter("whereSql", sql);
				 
				 juageDownTime(queryFilter, begindate, enddate, sbegindate, senddate, sql);
				 
			 }
			
			 //
			 if(begindate.length()!=0 && enddate.length()==0 ) {
				 String sql =   "ALLOCATEDTIME >=  '"+begindate+"'";
				 queryFilter.addParamsFilter("begin_ALLOCATEDTIME", Utils.string2Date(begindate));
				 queryFilter.addParamsFilter("whereSql", sql);
				 
				 juageDownTime(queryFilter, begindate, enddate, sbegindate, senddate, sql);
				 
				 
			 }
			 
			 //
			 if(begindate.length()==0 && enddate.length()!=0 ) {
				 String sql =   "ALLOCATEDTIME <=  '"+enddate+"'";
				 queryFilter.addParamsFilter("end_ALLOCATEDTIME", Utils.string2Date(enddate));
				 queryFilter.addParamsFilter("whereSql", sql);
				 
				 				 
				 juageDownTime(queryFilter, begindate, enddate, sbegindate, senddate, sql);
				 
			 }
			 */
			 
			
			
			 String listData=   this.currentPermissionQueryService.queryPage(queryFilter);
			 PageList<CurrentPermissionPo> currentPermissionList = null;
			if(JacksonUtil.isJsonObject(listData)){
				List<CurrentPermissionPo> list = CurrentPermissionPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				currentPermissionList = new PageList<CurrentPermissionPo>(list, pageResult);
			}
			
			return new PageJson(currentPermissionList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}


	private void juageDownTime(QueryFilter queryFilter, String begindate, String enddate, String sbegindate,
			String senddate, String sql) {
		//前台不为空，
		 //判断后面的选择情况
		 if(sbegindate.length()!=0 && senddate.length()!=0) {
			 String sql2 =  sql
				       +"and DOWNTIME >=  '"+begindate+"'"+"and DOWNTIME <=  '"+senddate+"'";
		 queryFilter.addParamsFilter("begin_DOWNTIME", Utils.string2Date(sbegindate));
		 queryFilter.addParamsFilter("end_DOWNTIME", Utils.string2Date(senddate));
		 
		 queryFilter.addParamsFilter("whereSql", sql2);
		 }else if(sbegindate.length()!=0&& senddate.length()==0 ) {
			 String sql2 =  sql
				       +"and DOWNTIME >=  '"+begindate+"'";
			 queryFilter.addParamsFilter("begin_DOWNTIME", Utils.string2Date(sbegindate));
			 queryFilter.addParamsFilter("whereSql", sql2);   
			 
		 }else if (sbegindate.length()==0 && senddate.length()!=0 ) {
			 String sql2 =   sql
				       + "DOWNTIME <=  '"+enddate+"'";
			 queryFilter.addParamsFilter("end_DOWNTIME", Utils.string2Date(senddate));
			 queryFilter.addParamsFilter("whereSql", sql2);  
		 }else {  //按照默认的查询
			 
		 }
	}
	
	
	@RequestMapping("userPermissionPage")
	 public ModelAndView userPermissionPage(HttpServletRequest request,HttpServletResponse response) throws Exception{
		  ModelAndView mv=getAutoView("/rdp/CurrentPermission/userPermissionList.jsp");
		  String usernum =  RequestUtil.getString(request, "usernum");
		  return mv.addObject("usernum", usernum);	  
	 }
	
	/**
	 * 【TB_DOOR_CURRENTPERMISSION】列表(分页条件查询)数据
	 *
	 * @param request
	 * @param reponse
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("userPermissionList")
	public @ResponseBody PageJson userPermissionList(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		QueryFilter queryFilter = getQuerFilter(request);
		String usernum = RequestUtil.getString(request, "usernum");
		queryFilter.addParamsFilter("studentno", usernum);
		try{
			String listData = currentPermissionQueryService.queryUserPermission(queryFilter);
			PageList<CurrentPermissionPo> currentPermissionList = null;
			if(JacksonUtil.isJsonObject(listData)){
				List<CurrentPermissionPo> list = CurrentPermissionPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				currentPermissionList = new PageList<CurrentPermissionPo>(list, pageResult);
			}
			
			return new PageJson(currentPermissionList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}
	
	
	
	/**
	 * 编辑【TB_DOOR_CURRENTPERMISSION】信息页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("edit")
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String preUrl= RequestUtil.getPrePage(request);
		String id=RequestUtil.getString(request, "id");
		CurrentPermissionPo currentPermission=null;
		if(StringUtil.isNotEmpty(id)){
			String data = null;
			data = currentPermissionQueryService.get(id);
			currentPermission = CurrentPermissionPo.fromJsonString(data);
		}

		return getAutoView().addObject("currentPermission", currentPermission).addObject("returnUrl", preUrl);
	}
	
	
	/**
	 * Edits the 2.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("edit2")
	public ModelAndView  edit2(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String preUrl= RequestUtil.getPrePage(request);
		//1.点击取消按钮 更新记录
		String[] ids=RequestUtil.getStringAryByStr(request, "id");
		
		CurrentPermissionPo currentPermission=null;
	  for (int i = 0; i < ids.length; i++) {
		  if(StringUtil.isNotEmpty(ids[i])){
				String data = null;
				//查询字段数值
				data = currentPermissionQueryService.get(ids[i]);
				//得到usernum,查询出usernum 所在的记录，每条记录全部更新
				currentPermission = CurrentPermissionPo.fromJsonString(data);
//				String uid=     currentPermission.getStudentuid();
//			 List<CurrentPermissionPo> currentPermissionList = currentPermissionQueryDao.findByKey("get1", uid);
//			   if(currentPermissionList.size()>0) {
//				   
//				   for (int j = 0; j < currentPermissionList.size(); j++) {
//					   //设置更新字段
//						currentPermissionList.get(j).setPermissionstatus(""+2);
//						//清空信息，设置下发时间为空
//						currentPermissionList.get(j).setDowntime(null);
//						currentPermissionList.get(j).setAllocatedtime(new Date());
//						//更新数据
//						currentPermissionRepository.newInstance(currentPermissionList.get(j)).update();
//				}
				
				currentPermission.setPermissionstatus(""+2);
//				//清空信息，设置下发时间为空
				currentPermission.setDowntime(null);
				currentPermission.setAllocatedtime(new Date());
				//更新数据
//				currentPermissionRepository.newInstance(currentPermission).update();
			    this.currentPermissionService.update(currentPermission);
			
				
//			   }else {
//				   
//			   }
				
				
			}
			//2.向历史表插入数据
//			  CurrentPermissionHisPo currentPermissionHisPo=new CurrentPermissionHisPo();
//			  currentPermissionHisPo.setPermissionid(currentPermission.getPermissionid());
//			  currentPermissionHisPo.setStudentno(currentPermission.getStudentno());
//			  currentPermissionHisPo.setStudentuid(currentPermission.getStudentuid());
//			  currentPermissionHisPo.setDoorno(currentPermission.getDoorno());
//			  currentPermissionHisPo.setControllerno(currentPermission.getControllerno());
//			  currentPermissionHisPo.setPermissiontype(currentPermission.getPermissiontype());
//			  currentPermissionHisPo.setPermissionstatus("2");
//			  currentPermissionHisPo.setAllocatedtime(currentPermission.getAllocatedtime());
//			  currentPermissionHisPo.setDowntime(currentPermission.getDowntime());
//			  currentPermissionHisPo.setTimeseg(currentPermission.getTimeseg());
//			  currentPermissionHisPo.setUserpassword(currentPermission.getUserpassword());
//			  currentPermissionHisPo.setEffecttime(currentPermission.getEffecttime());
//			  currentPermissionHisPo.setStarttime(currentPermission.getStarttime());
//			  currentPermissionHisPo.setEndtime(currentPermission.getEndtime());
//			  currentPermissionHisPo.setPermissiongroup(currentPermission.getPermissiongroup());
//			  currentPermissionHisPo.setServicecode(currentPermission.getServicecode());
//			  currentPermissionHisPo.setExt1(currentPermission.getExt1());
//			  currentPermissionHisPo.setExt2(currentPermission.getExt2());
//			  currentPermissionHisPo.setExt3(currentPermission.getExt3());
//			  currentPermissionHisPo.setExt4(currentPermission.getExt4());
//			  currentPermissionHisPo.setExt5(currentPermission.getExt5());
//			  currentPermissionHisPo.setExt6(currentPermission.getExt6());
//			CurrentPermissionHisRepository.newInstance(currentPermissionHisPo).create();
	}
         String jspPath="/rdp/CurrentPermission/currentPermissionList.jsp";
		return new ModelAndView(jspPath);
	}
	
	
	
	
	/**
	 * 编辑【TB_DOOR_CURRENTPERMISSION】信息页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("flowEdit")
	public ModelAndView flowEdit(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String preUrl= RequestUtil.getPrePage(request);
		String id=RequestUtil.getString(request, "id");
		CurrentPermissionPo currentPermission=null;
		if(StringUtil.isNotEmpty(id)){
			String data = null;
			data = currentPermissionQueryService.get(id);
			currentPermission = CurrentPermissionPo.fromJsonString(data);
		}
		return getAutoView().addObject("currentPermission", currentPermission).addObject("returnUrl", preUrl);
	}
	
	/**
	 * 【TB_DOOR_CURRENTPERMISSION】明细页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("get")
	public ModelAndView get(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String preUrl= RequestUtil.getPrePage(request);
		String id=RequestUtil.getString(request, "id");
		CurrentPermissionPo currentPermission=null;
		if(StringUtil.isNotEmpty(id)){
			String data = null;
			data = currentPermissionQueryService.get(id);
			currentPermission = CurrentPermissionPo.fromJsonString(data);
		}
		return getAutoView().addObject("currentPermission", currentPermission).addObject("returnUrl", preUrl);
	}
	
	/** 
	 * 保存【TB_DOOR_CURRENTPERMISSION】信息
	 *
	 * @param request
	 * @param response
	 * @param  currentPermission
	 * @throws Exception
	 */
	@RequestMapping("save4")
	public void save4(@RequestBody String json,HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMessage message=null;
		try {
		
			currentPermissionService.save(json);
			message=new ResultMessage(ResultMessage.SUCCESS, "保存TB_DOOR_CURRENTPERMISSION成功");
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "对TB_DOOR_CURRENTPERMISSION操作失败,"+e.getMessage());
			logger.error("对TB_DOOR_CURRENTPERMISSION操作失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	
	
	
	
	@RequestMapping("save3")
	public void save3(@RequestBody PreParam pararm,HttpServletRequest request,HttpServletResponse response) throws Exception{
  		ResultMessage message=null;
		try {
			   //获取数值
			    List<String> userArr = pararm.getUseArr();
			    String timeseqment=pararm.getStr();

			    List<String> doorArr = pararm.getDoorArr();
			    List<String> doorArrs = filterChar(doorArr);
			    
			    //过滤 特殊符号
			    String startTime = pararm.getStartTime();			
			    String endTime = pararm.getEndTime();

		        List<List<String>> dimvalue = new ArrayList<List<String>>();
		        dimvalue.add(userArr);
		        dimvalue.add(doorArrs);
		        List<String> result = new ArrayList<String>();
		        Descartes.run(dimvalue, result, 0, "");
		        

		        for (String s : result)
		        {
			        String[] record = s.split(",");
			        String studentno = record[0];
			        CampusCardPo po = campusCardQueryService.getByUserNum(studentno);
			        String studentuid = po.getCarduid();
			        String doorno=record[1]; 
			        String doorname=record[2];
			        //当前时间//设置日期格式
			        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			     // new Date()为获取当前系统时间，也可使用当前时间戳
			        String date = df.format(new Date());

			  		//组装bean	  
					CurrentPermissionPo currentPermissionPo=new CurrentPermissionPo();
					currentPermissionPo.setPermissionid("");
					currentPermissionPo.setStudentno(studentno); //这里界面显示为学生姓名						 
					currentPermissionPo.setStudentuid(studentuid);
					currentPermissionPo.setDoorno(doorno);
					currentPermissionPo.setControllerno(doorname);
					currentPermissionPo.setPermissiontype("0x50");
					currentPermissionPo.setPermissionstatus("0");
					currentPermissionPo.setAllocatedtime(string2Date(date)); //插入当前时间戳 date2String

						  
				   if(null==timeseqment) {
					   timeseqment="1";
				   }
				 //插入当前时间段
				  currentPermissionPo.setTimeseg(timeseqment); 
				  currentPermissionPo.setUserpassword("");
				  currentPermissionPo.setEffecttime(date2String(new Date()));
				  currentPermissionPo.setStarttime(string2Date2(startTime));
				  currentPermissionPo.setEndtime(string2Date2(endTime));
				  currentPermissionPo.setPermissiongroup("");
				  currentPermissionPo.setServicecode(servicecode);
				  
				  currentPermissionPo.setExt1("1"); //标识用户授权
				  currentPermissionPo.setExt2("");
				  currentPermissionPo.setExt3("");
				  currentPermissionPo.setExt4("");
				  currentPermissionPo.setExt5("");
				  currentPermissionPo.setExt6("");

//				  currentPermissionRepository.newInstance(currentPermissionPo).create();
                  this.currentPermissionService.create(currentPermissionPo);
			  			
			 }
			        
			
			
		      
			
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "对TB_DOOR_CURRENTPERMISSION操作失败,"+e.getMessage());
			logger.error("对TB_DOOR_CURRENTPERMISSION操作失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}

	

	
	
	@RequestMapping("query")
	public void query(@RequestBody PreParam pararm,HttpServletRequest request,HttpServletResponse response) throws Exception{
  		ResultMessage message=null;
	    //过滤 特殊符号
	    String startTime = pararm.getStartTime();			
	    String endTime = pararm.getEndTime();
	    String timeseqment=pararm.getStr();
  		StringBuffer sb=new StringBuffer();
		try {
			    //获取用戶
			    List<String> userArr = pararm.getUseArr();
			    //获取門
			    List<String> doorArr = pararm.getDoorArr();
			    List<String> doorArrs = filterChar(doorArr);
			    

                //門和用戶
		        List<List<String>> dimvalue = new ArrayList<List<String>>();
		        dimvalue.add(userArr);
		        dimvalue.add(doorArrs);		        
		        List<String> result = new ArrayList<String>();
		        Descartes.run(dimvalue, result, 0, "");
		        
		        for (String s : result)
		        {
			 //解析字符串
			        String[] record = s.split(",");
			        String studentno=record[0];
			        String doorno=record[1]; 
				    //根据uid,和doono 查询，该纪录是否存在，存在则提示终止操作，否则插入
			        Map hashmap=new HashMap<String, String>(256);
			        hashmap.put("doorno", doorno);
			        hashmap.put("studentno", studentno);

			        List<CurrentPermissionPo> list = this.currentPermissionQueryService.queryByUserNoAndDoor(hashmap);
			         if(BeanUtils.isEmpty(list)) {
			        	 continue;			        				        	 
			         }else { //
			        	 String doorname=null;
					      
					    //遍历出List 
			        	   for (int i = 0; i < list.size(); i++) {
					                  
			        		 studentno= list.get(i).getStudentno();
			        		 doorname = list.get(i).getControllerno();
			        		     sb.append("学工号："+studentno+"\t"+"门名称："+doorname).append("\n<br/>");
					          }
		          
			        	 
			         }			       			        			         
			  	}
		        
		        if(StringUtil.isNotEmpty(sb.toString())) {
		        	 sb.append("记录已经存在\n");
		        }
		       
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.ERROR, "操作失败"+e.getMessage());
			logger.error("对TB_DOOR_CURRENTPERMISSION操作失败，" + e.getMessage(),e);
		}
		
		if(sb.toString().length()>0) {
			message=new ResultMessage(ResultMessage.SUCCESS,sb.toString());
		}else {
			message=new ResultMessage(ResultMessage.FAIL,sb.toString());
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	

	
	@RequestMapping("update")
	public void update(@RequestBody PreParam pararm,HttpServletRequest request,HttpServletResponse response) throws Exception{
  		ResultMessage message=null;
		try {
			
			  //获取数值
			    String timeseqment=pararm.getStr();
			    //过滤 特殊符号
			    String startTime = pararm.getStartTime();
			    String endTime = pararm.getEndTime();
			    List<String> userArr = pararm.getUseArr();
			    List<String> doorArr = pararm.getDoorArr();
			    List<String> doorArrs = filterChar(doorArr);
			    
		        List<List<String>> dimvalue = new ArrayList<List<String>>();
		        dimvalue.add(userArr);
		        dimvalue.add(doorArrs);
		        List<String> result = new ArrayList<String>();
		        Descartes.run(dimvalue, result, 0, "");

		        for (String s : result)
		        {
			        //解析字符串
			        String[] record = s.split(",");
			        String studentno = record[0];
			        CampusCardPo po = campusCardQueryService.getByUserNum(studentno);
			        String studentuid = po.getCarduid();
			        String doorno=record[1]; 
			        String doorname=record[2];				     
			        Map hashmap=new HashMap<String, String>(256);
			        hashmap.put("doorno", doorno);
			        hashmap.put("studentno", studentno);

			      //  List<CurrentPermissionPo> list = currentPermissionQueryDao.findByKey("queryByUserNoAndDoor", hashmap);
			        
			        // 调用service 方法
			        
			        List<CurrentPermissionPo> list = this.currentPermissionQueryService.queryByUserNoAndDoor(hashmap);
			        
			        if(BeanUtils.isNotEmpty(list)) {
			        	
			        	list.get(0).setPermissionstatus("0");
			 			//更新数据
//			 			currentPermissionRepository.newInstance(list.get(0)).update();
			 			 this.currentPermissionService.update(list.get(0));
			        }else {
				  		//组装bean	  
						CurrentPermissionPo currentPermissionPo=new CurrentPermissionPo();
						currentPermissionPo.setPermissionid("");
						currentPermissionPo.setStudentno(studentno); //这里界面显示为学生姓名						 
						currentPermissionPo.setStudentuid(studentuid);
						currentPermissionPo.setDoorno(doorno);
						currentPermissionPo.setControllerno(doorname);
						currentPermissionPo.setPermissiontype("0x50");
						currentPermissionPo.setPermissionstatus("0");
				        //当前时间
				        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				     // new Date()为获取当前系统时间，也可使用当前时间戳
				        String date = df.format(new Date());
						currentPermissionPo.setAllocatedtime(string2Date(date)); //插入当前时间戳 date2String
							  
					   if(null==timeseqment ) {
						   timeseqment="1";
					   }
					  
					  currentPermissionPo.setTimeseg(timeseqment); //插入当前时间段
					  currentPermissionPo.setUserpassword("");
					  currentPermissionPo.setEffecttime(date2String(new Date()));
					  currentPermissionPo.setStarttime(string2Date2(startTime));
					  currentPermissionPo.setEndtime(string2Date2(endTime));
					  currentPermissionPo.setPermissiongroup("");
					  currentPermissionPo.setServicecode(servicecode);
					 currentPermissionPo.setExt1("1"); //标识用户授权
					  currentPermissionPo.setExt2("");
					  currentPermissionPo.setExt3("");
					  currentPermissionPo.setExt4("");
					  currentPermissionPo.setExt5("");
					  currentPermissionPo.setExt6("");
//					  currentPermissionRepository.newInstance(currentPermissionPo).create();
					  this.currentPermissionService.create(currentPermissionPo);
			        }
				  		
			        
			  	}
		        
			
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "对TB_DOOR_CURRENTPERMISSION操作失败,"+e.getMessage());
			logger.error("对TB_DOOR_CURRENTPERMISSION操作失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	

	
	 /**
     * 将Date类型转换成String类型
     * @param date Date对象
     * @return 形如:"yyyy-MM-dd HH:mm:ss"
     */
    public static String date2String(Date date)
    {
        return date2String(date,"yyyy-MM-dd HH:mm:ss");
    }
    /**
     * 将Date按格式转化成String
     * @param date    Date对象
     * @param pattern 日期类型
     * @return String
     */
    public static String date2String(Date date,String pattern)
    {
        if(date == null || pattern == null)
        {
            return null;
        }
        return new SimpleDateFormat(pattern).format(date);
    }
	/**
     * 将String类型转换成Date类型
     *
     * @param date Date对象
     * @return
     */
    public static Date string2Date(String date)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return format.parse(date);
        } catch (ParseException e) {
           
            return null;
        }
    }
    
    
//    public static Date string2Date3(String date)
//    {
//        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
//        try {
//            return format.parse(date);
//        } catch (ParseException e) {
//           
//            return null;
//        }
//    }
    
    public static Date string2Date2(String date)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        try {
            return format.parse(date);
        } catch (ParseException e) {
           
            return null;
        }
    }
    
    
	private List<String> filterChar(List<String> userArr) {
		String str;
		List<String> userArrs=new ArrayList<String>();
		for (int i = 0; i < userArr.size(); i++) {
			 str = userArr.get(i);
			 if(str.contains("|")) {
				 str = str.substring(0,str.length()-1);
			 }
			 userArrs.add(str);
		}
		return userArrs;
	}
	
	
	/** 
	 * 保存【TB_DOOR_CURRENTPERMISSION】信息
	 *
	 * @param request
	 * @param response
	 * @param  currentPermission
	 * @throws Exception
	 */
	@RequestMapping("save")
	public void save(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMessage message=null;
		try {
			String json = RequestUtil.getString(request, "json");
			currentPermissionService.save(json);
			message=new ResultMessage(ResultMessage.SUCCESS, "保存TB_DOOR_CURRENTPERMISSION成功");
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "对TB_DOOR_CURRENTPERMISSION操作失败,"+e.getMessage());
			logger.error("对TB_DOOR_CURRENTPERMISSION操作失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	/**
	 *  批量删除【TB_DOOR_CURRENTPERMISSION】记录
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("remove")
	public void remove(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMessage message=null;
		try {
			//获得待删除的id
			String[] ids=RequestUtil.getStringAryByStr(request, "id");
			currentPermissionService.deleteByIds(ids);
			message=new ResultMessage(ResultMessage.SUCCESS, "删除TB_DOOR_CURRENTPERMISSION成功");
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "删除TB_DOOR_CURRENTPERMISSION失败，" + e.getMessage());
			logger.error("删除TB_DOOR_CURRENTPERMISSION失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	
	
	
	
	

}